// src/utils/rules.ts
import type { FormRules } from 'element-plus'
import type { Ref } from 'vue'
export interface IFormData {
  email: string
  password: string
  checkCode: string
  nickName?: string
  registerPassword?: string
}
/**
 * 通用表单校验规则
 */
export const useFormRules = <T extends IFormData>(formData: Ref<T>) => {
  /** 邮箱校验 */
  const emailRule = [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/,
      message: '请输入正确的邮箱格式',
      trigger: ['blur', 'change']
    }
  ]

  /** 密码校验（6-20位字母+数字） */
  const passwordRule = [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^[0-9]*$/,
      // pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/,
      message: '6-20位字母和数字组合',
      trigger: ['blur', 'change']
    }
  ]

  /** 确认密码校验（需与password字段一致） */
  const confirmPasswordRule = <K extends keyof T>(compareField: K) => {
    return [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (rule: unknown, value: string, callback: (error?: Error) => void) => {
          if (value !== formData.value[compareField]) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }

  /** 验证码校验（4-6位数字） */
  const checkCodeRule = [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      pattern: /^(-?[0-9]\d*)$/,
      message: '请输入验证码',
      trigger: ['blur', 'change']
    }
  ]

  /** 昵称校验（2-10位字符） */
  const nickNameRule = [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '昵称为2-10个字符',
      trigger: 'blur'
    }
  ]

  return {
    emailRule,
    passwordRule,
    confirmPasswordRule,
    checkCodeRule,
    nickNameRule
  }
}

// 导出类型
export type FormRulesType = ReturnType<typeof useFormRules>
